package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        // 获取用户信息（通过 username 查询）
        SysUser user = sysUserService.selectUserByUserName(loginBody.getUsername());

        Set<String> roles = permissionService.getRolePermission(user);
        boolean needSelectRole = roles == null || roles.isEmpty();

        return AjaxResult.success()
                .put(Constants.TOKEN, token)
                .put("needSelectRole", needSelectRole);
    }

    /**
     * 登录方法
     *手机验证码登录
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/phone")
    public AjaxResult loginByPhone(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginByPhoneAndCaptcha(loginBody.getPhoneNumber(), loginBody.getCode(),
                loginBody.getUuid());
        // 获取用户信息（通过 username 查询）
        SysUser user = sysUserService.selectUserByPhonenumber(loginBody.getPhoneNumber());

        Set<String> roles = permissionService.getRolePermission(user);
        boolean needSelectRole = roles == null || roles.isEmpty();

        return AjaxResult.success()
                .put(Constants.TOKEN, token)
                .put("needSelectRole", needSelectRole);
    }

    @GetMapping("/getAllRoles")
    public AjaxResult getAllRoles() {
        List<String> roles = permissionService.getAllRoles();
        // 过滤掉 "超级管理员"
        List<String> filteredRoles = roles.stream()
                .filter(role -> !"超级管理员".equals(role))
                .collect(Collectors.toList());
        return AjaxResult.success("roles", filteredRoles);
    }


    @PostMapping("/select/role")
    public AjaxResult assignRole(@RequestBody Map<String, String> body) {
        System.out.println("接收到的角色名: " + body.get("role"));  // 打印接收到的角色名
        String roleName = body.get("role");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();

        loginService.assignRoleToUser(user.getUserId(), roleName);

        return AjaxResult.success("角色分配成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
